package com.selebash.runtime.resource;

import com.selebash.exception.SelebashException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

/**
 * @author sad
 */
public class JarResourceManager extends ResourceManager {

    @Override
    public boolean isExist(String path) {
        InputStream stream = JarResourceManager.class.getResourceAsStream(path);
        if (stream != null) {
            try {
                stream.close();
                return true;
            } catch (IOException ex) {
                throw new SelebashException("Cannot close stream for jar resource: " + path);
            }
        }
        return false;
    }

    @Override
    public String getContent(String path) {
        InputStream stream = JarResourceManager.class.getResourceAsStream(path);
        if (stream == null) {
            throw new SelebashException("Jar resource " + path + " is not found");
        }
        try {
            String value = IOUtils.toString(stream, "UTF8");
            stream.close();
            return value;
        } catch (IOException ex) {
            throw new SelebashException("Cannot read data from jar resource " + path);
        }
    }

    @Override
    public String combinePath(String path1, String path2) {
        if (path1.endsWith("/")) {
            path1 = path1.substring(0, path1.length() - 1);
        }

        if (path2.startsWith("/")) {
            path2 = path2.substring(1);
        }

        return path1 + "/" + path2;
    }

}
